/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.utils;

public abstract class Watchdog implements ThreadScheduable {

	private int frequency = 5000;
	private Barkable barkable = null;

	/**
	 * Frequency - At what frequency should shouldBark be called in milli secs
	 */
	public Watchdog(int frequency,Barkable barkable) {
		ThreadSchedule.add(this);
		this.barkable = barkable;
	}

	public boolean keepAlive() {return true;}
	public int sleepTime() {return frequency;}

	public void process()
	throws Throwable {
		if (shouldBark()) {
			barkable.barkDog();
		}
	}

	public void close() throws Throwable {}

	/**
	 * Has an event occurred that the dog should bark
	 */
	abstract boolean shouldBark();

	public static interface Barkable {
		void barkDog();
	}

	public static class WatchIpChange extends Watchdog {
		private String last_address = null;

		public WatchIpChange(int frequency,Barkable barkable) {
			super(frequency,barkable);
		}

		public boolean shouldBark() {
			try {
				if (last_address == null) {
					last_address = java.net.InetAddress.getLocalHost().getHostAddress();
					return false;
				} else if (!java.net.InetAddress.getLocalHost().getHostAddress().equals(last_address)) {
					return true;
				}
			} catch (Throwable th) {
				Log.debug.out(th);
			}
			return false;
		}
	}

	public static class WatchTest extends Watchdog {
		private String last_address = null;
		private long LAST_EXEC = System.currentTimeMillis(),frequency = 20000;

		public WatchTest(int frequency,Barkable barkable) {
			super(5000,barkable);
			this.frequency = frequency;
		}

		public boolean shouldBark() {
			if (System.currentTimeMillis() - LAST_EXEC > frequency) {
				LAST_EXEC = System.currentTimeMillis();
				return true;
			} else {
				return false;
			}
		}
	}
}

